//
//  TaskWallSystem.m
//  Fucker
//
//  Created by Coby on 17/9/5.
//  Copyright © 2017年 梦拓科技. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "TaskWallSystem.h"
#import "ZGInfoCollection.h"
//#import <UIKit/UIApsplication.h>
#import "AFNetworking.h"
//#import "ViewController.h"
#import "Common.h"

@implementation TaskWallSystem

+ (TaskWallSystem*)sharedInstance;
{
    static TaskWallSystem * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[TaskWallSystem alloc] init];
    });
    return instance;
}

//###5、获取新增任务列表、活跃任务列表、充值任务列表(广告商下面的子账号才能够获取对应的任务,根据排期优先级不同不同),默认返回10个### (Test OK) Path: /requestServiceList Method: POST Params: userId,用户id deviceId,设备唯一标识, deviceString:手机型号,目前支持的值为iPhone5,3,iPhone5,4,iPhone6,1,iPhone6,2,iPhone7,1,iPhone7,2,iPhone8,1,iPhone8,2 systemVersion:字符串如8.0 9.3.3 appVersion:香蕉系统版本号如0.0.1
-(void)requestServiceList:(void (^)(void))callback
{
    NSMutableDictionary * result = [NSMutableDictionary dictionary];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSString * requestTask = [BaseServer stringByAppendingString: @"/requestServiceList"];
    NSDictionary * parameters = @{
                                  @"userId":_userId,
                                  @"deviceId":_deviceId,
                                  @"deviceString":_deviceString,//Iphone 6s
                                  @"systemVersion":_systemVersion,
                                  @"appVersion":_appVersion
                                  };
    OOLog(@"requestServiceList Parameter:%@",parameters);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //    manager.responseSerializer = [RNJSONResponseSerializer serializer];
    
    [manager POST:requestTask parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (responseObject) {
            [result addEntriesFromDictionary:responseObject];
        }
//        OOLog(@"--> requestServiceList %@", result);
        if([result[@"code"] integerValue]==1){
            _chargeQuestList=result;
        }
        callback();

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSLog(@"URL REQUESET FAIL");
    }];
}


- (void)requestSelectedTaskWithParam:(NSMutableDictionary *)param  requestURL:(NSString *)requestURL taskType:(int)taskType callback:(void (^)(void))callback {
    
    NSMutableDictionary * result = [NSMutableDictionary dictionary];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSString * requestTask = [BaseServer stringByAppendingString: requestURL];
    NSDictionary * parameters = @{
                                  @"userId":_userId,
                                  @"service_id":param[@"ServiceId"],
                                  @"service_daily_id":param[@"ServiceDailyId"],
                                  @"deviceId":_deviceId,
                                  @"deviceString":_deviceString,//Iphone 6s
                                  @"systemVersion":_systemVersion,
                                  };
    OOLog(@"requestServiceList Parameter:%@",parameters);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:requestTask parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (responseObject) {
            [result addEntriesFromDictionary:responseObject];
        }
        
        OOLog(@"requestTaskRecharge %@", result);
        _ChargeTaskList=result;
        if([_ChargeTaskList[@"code"] intValue]==1){
            _ChargeTaskList[@"ChargeHelperState"]=@"1";
            _ChargeTaskList[@"TaskType"]=[NSString stringWithFormat:@"%d",taskType];
            _ChargeTaskList[@"QStarttime"]=[NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
            
            [_ChargeTaskList writeToFile:TaskFile  atomically:YES];
            
        }
        callback();
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSLog(@"URL REQUESET FAIL");
    }];
}

- (void)baseRequestWithParam:(NSDictionary *)param requestURL:(NSString *)requestURL succeededBlock:(void(^)(id responseObject))succeededData errorBlock:(void(^)(NSError *error))errorData {
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSString * requestTask = [BaseServer stringByAppendingString: requestURL];
    
    OOLog(@"requestServiceList Parameter:%@",param);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:requestTask parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        succeededData(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        errorData(error);
    }];
}

- (void)requestUseGetWithParam:(NSDictionary *)param requestURL:(NSString *)requestURL succeededBlock:(void(^)(id responseObject))succeededData errorBlock:(void(^)(NSError *error))errorData {
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSString * requestTask = [BaseServer stringByAppendingString: requestURL];
    
    OOLog(@"requestServiceList Parameter:%@",param);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:requestTask parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        succeededData(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        errorData(error);
    }];
}

-(void)requestTaskRecharge:(void (^)(void))callback
{
    NSMutableDictionary * result = [NSMutableDictionary dictionary];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSString * requestTask = [BaseServer stringByAppendingString: @"/requestTaskRecharge"];
    NSDictionary * parameters = @{
                                  @"userId":_userId,
                                  @"service_id":[[TaskWallSystem sharedInstance] SelectedTaskFromList][@"ServiceId"],
                                  @"service_daily_id":[[TaskWallSystem sharedInstance] SelectedTaskFromList][@"ServiceDailyId"],
                                  @"deviceId":_deviceId,
                                  @"deviceString":_deviceString,
                                  @"systemVersion":_systemVersion,
                                  @"appVersion":_appVersion
                                  };
    OOLog(@"requestTask:%@-Parameter:%@",requestTask,parameters);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:requestTask parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (responseObject) {
            [result addEntriesFromDictionary:responseObject];
        }
        OOLog(@"requestTaskRecharge %@", result);
        _ChargeTaskList=result;
        if([_ChargeTaskList[@"code"] intValue]==1){
            _ChargeTaskList[@"ChargeHelperState"]=@"1";
            _ChargeTaskList[@"QStarttime"]=[NSString stringWithFormat:@"%ld", (NSInteger)[[NSDate date] timeIntervalSince1970]];
             OOLog(@"ChargeTaskList write to file %@", _ChargeTaskList);
            
             [_ChargeTaskList writeToFile:TaskFile  atomically:YES];
        
        }
        callback();
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSLog(@"URL REQUESET FAIL");
    }];
}

-(void)requestdeviceRecycle:(void (^)(void))callback
{
    NSMutableDictionary * result = [NSMutableDictionary dictionary];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSString * requestTask = [BaseServer stringByAppendingString: @"/deviceRecycle"];
    NSDictionary * parameters = @{
                                  @"userId":_userId,
                                  @"deviceId":_deviceId,
                                  @"deviceString":_deviceString,
                                  @"systemVersion":_systemVersion,
                                  @"appVersion":_appVersion
                                  };
    OOLog(@"Parameter:%@",parameters);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //    manager.responseSerializer = [RNJSONResponseSerializer serializer];
    
    [manager POST:requestTask parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        OOLog(@"requestdeviceRecycle responseObject %@", responseObject);

        if (responseObject) {
            [result addEntriesFromDictionary:responseObject];
        }
        OOLog(@"requestdeviceRecycle %@", result);
        _ChargeTaskList=result;
        if([_ChargeTaskList[@"code"] integerValue]==1){
        }
        callback();
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSLog(@"URL REQUESET FAIL");
    }];
}

-(void)commitTask:(void (^)(void))callback
{
    NSMutableDictionary * result = [NSMutableDictionary dictionary];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSString * requestTask = [BaseServer stringByAppendingString: @"/commitTask"];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:_userId forKey:@"userId"];
    [parameters setObject:_ChargeTaskList[@"data"][@"Phone"] forKey:@"damaPhoneNumber"];
    [parameters setObject:_ChargeTaskList[@"data"][@"TaskId"] forKey:@"taskId"];
    [parameters setObject:_ChargeTaskList[@"data"][@"ServiceId"] forKey:@"service_id"];
    [parameters setObject:_ChargeTaskList[@"data"][@"ServiceDailyId"] forKey:@"service_daily_id"];
    [parameters setObject:_ChargeTaskList[@"data"][@"Phone"] forKey:@"damaPhoneNumber"];
    [parameters setObject:_CommitParamaList[@"onlineTime"] forKey:@"onlineTime"];
    [parameters setObject:@"" forKey:@"gameArea"];
    [parameters setObject:_CommitParamaList[@"manulArea"] forKey:@"manulArea"];
    [parameters setObject:_CommitParamaList[@"manuLevelStart"] forKey:@"manuLevelStart"];
    [parameters setObject:_CommitParamaList[@"manuLevelEnd"] forKey:@"manuLevelEnd"];
    [parameters setObject:_deviceId forKey:@"deviceId"];
    [parameters setObject:_deviceString forKey:@"deviceString"];
    [parameters setObject:_systemVersion forKey:@"systemVersion"];
    [parameters setObject:_appVersion forKey:@"appVersion"];
    
    NSLog(@"Parameter:%@",parameters);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:requestTask parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if (responseObject) {
            [result addEntriesFromDictionary:responseObject];
        }
        OOLog(@"commitTask %@", result);
        _Commitresult=result;
        callback();
        if([_Commitresult[@"code"] integerValue]==1){
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSLog(@"URL REQUESET FAIL");
    }];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        NSFileManager * fileManger = [NSFileManager defaultManager];
        if([fileManger fileExistsAtPath:TaskUserSettingFile isDirectory:false]==true){
            NSMutableDictionary * tempMutableDictionary=[NSMutableDictionary dictionaryWithContentsOfFile:TaskUserSettingFile];
            if (tempMutableDictionary[@"userID"]){
                _userId=tempMutableDictionary[@"userID"];
            }
            if (tempMutableDictionary[@"serviceid"]){
                _service_id=tempMutableDictionary[@"serviceid"];
            }
            
            if (tempMutableDictionary[@"boundleID"]) {
                _boundleId = tempMutableDictionary[@"boundleID"];
            }
            
            if (tempMutableDictionary[@"type"]) {
                _type = tempMutableDictionary[@"type"];
            }
        }
//        _deviceId=[[ZGDeviceInfo currentDeviceInfo] getUUID];
        
        if ([fileManger fileExistsAtPath:UserDeviceIDFile isDirectory:false]==true) {
            
            NSMutableDictionary *muDict = [NSMutableDictionary dictionaryWithContentsOfFile:UserDeviceIDFile];
            if (muDict != nil) {
                _deviceId = muDict[@"deviceId"];
            }else {
                
                _deviceId = @"";
            }
        }else {
           
            _deviceId = @"";
        }
        
        _deviceString=[[ZGDeviceInfo currentDeviceInfo] getCurrentDevicePhoneType];
        _systemVersion=[[ZGDeviceInfo currentDeviceInfo] getSystemVersion];
        _appVersion=@"0.01";
        _rechargetQuestState=ChargeNull;
        
        _chargeQuestList=nil;
    }
    return self;
}



@end
